package com.momo.hotel.utils;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;
import java.util.UUID;

/**
 * @version 1.0.0
 * @auther Snake
 * @date 2019/7/5 22:32
 */
public class UploadFile {

    public static String uploadFile(HttpServletRequest request, MultipartFile file, String str) throws ServletException, IOException {

        //获取文件原名
        String filename = file.getOriginalFilename();
        //获取存储路径
        String path = request.getSession().getServletContext().getRealPath(str);
        //获取文件后缀
        String fileSuffix = filename.substring(filename.indexOf("."), filename.length());

        File file1 = new File(path);
        //创建文件夹
        if(!file1.exists()){
            file1.mkdirs();
        }
        //创建文件对象
        String newFileName = UUID.randomUUID()+fileSuffix;
        file1 = new File(path,newFileName);
        System.out.println(file1.getAbsolutePath());
        if(!file1.exists()){
            try {
                file1.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            // 写入文件
            file.transferTo(file1);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return newFileName;


    }
}
